package android.explorer;
import java.io.File;

import myultility.IconContextMenu;
import myultility.IconContextMenu.IconContextMenuOnClickListener;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.res.Resources;
import android.explorer.R.string;
import android.explorer.activity.FileCopy;
import android.explorer.dialogUltility.ShowOkDialog;
import android.explorer.dialogUltility.ShowYesNoDialog;
import android.explorer.interfaces.CallBack;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class Explorer extends Activity{

	final int properpties=0x00000;
	final int delete=0x0022;
	ListView list;
	View viewMain;
	IconContextMenu iconContextMenu = null;
	private final int CONTEXT_MENU_ID = 1;
	private final int MENU_ITEM_PROPERTIES = 	1;
	private final int MENU_ITEM_OPEN = 			2;
	private final int MENU_ITEM_RENAME =		3;
	private final int MENU_ITEM_COPY = 			4;
	private final int MENU_ITEM_CUT = 			5;
	private final int MENU_ITEM_PASTE = 		6;
	private final int MENU_ITEM_DELETE = 		7;
	
	boolean create=false;
	String lastPath="",selectPath;
	boolean isCopy=true;
	TextView tv;
	int select=-1;
	private String currentPath="/";
	
	boolean contextMenu = false;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        try{
        	setContentView(R.layout.main); 
	       
        	// path current
            tv=(TextView)findViewById(R.id.current);
	        
            // list view	***************************************
	    	list=(ListView)findViewById(R.id.list);
            
	    	list.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
				public void onItemSelected(AdapterView<?> arg0, View v,
						int arg2, long arg3) {
					selectPath=((ViewHolder)v.getTag()).getFilePath();
					select=arg2;
					Log.v("select","has select" );
				}
				public void onNothingSelected(AdapterView<?> arg0) {
					selectPath=null;
					select=-1;
					Log.v("select", "has unSelect");
				}
	          });

	        list.setAdapter(new DirectoryAdapter(this,getChild("/")));

	        list.setOnItemClickListener(new OnItemClickListener() {
	   		public void onItemClick(AdapterView<?> a, View v, int position, long id) 
	   		{
	   			String path="";
	   			try{
	   				ViewHolder item = (ViewHolder)v.getTag();
	   				path=item.getFilePath();
	   				Log.v("debug path",path == null ? "***nul***":path);
	   				if(path==null)return;
	   				if(!new File(path).isFile())
	   					list.setAdapter(new DirectoryAdapter(Explorer.this,getChild(path)));
	   				else{
	   					actionOpen(path);
	   				}
	   	        }catch(Exception e){
	   	        }
	   		 }
	   		});
	        
	        list.setOnItemLongClickListener(new OnItemLongClickListener() {

				public boolean onItemLongClick(AdapterView<?> arg0, View v,
						int arg2, long arg3) {
					selectPath=((ViewHolder)v.getTag()).getFilePath();
					select=arg2;
					showDialog(CONTEXT_MENU_ID);
					//iconContextMenu.
					return true;
				}
			});
	        // end list view	*********************************
	        
	        // context menu	************************************
	        Resources res = getResources();
	        iconContextMenu = new IconContextMenu(this, CONTEXT_MENU_ID);
	        iconContextMenu.addItem(res, "Properties", R.drawable.menuinfo,MENU_ITEM_PROPERTIES );
	        iconContextMenu.addItem(res, "Open...", R.drawable.menuinfo,MENU_ITEM_OPEN );
	        iconContextMenu.addItem(res, "Rename", R.drawable.menurename,MENU_ITEM_RENAME );
	        iconContextMenu.addItem(res, "Copy", R.drawable.menucopy,MENU_ITEM_COPY );
	        iconContextMenu.addItem(res, "Cut", R.drawable.menucut,MENU_ITEM_CUT );
	        iconContextMenu.addItem(res, "Paste", R.drawable.menupaste,MENU_ITEM_PASTE );
	        iconContextMenu.addItem(res, "Delete", R.drawable.menudelete,MENU_ITEM_DELETE );
	        
	    	iconContextMenu.setOnClickListener(new IconContextMenuOnClickListener() {
				
				public void onClick(int menuId) 
				{
					// TODO Auto-generated method stub
					switch(menuId)
					{
						case (MENU_ITEM_PROPERTIES):
						{
							actionProperties();
							break;
						}
						
						case (MENU_ITEM_OPEN):
						{
							
			   				if(!new File(selectPath).isFile())
			   					list.setAdapter(new DirectoryAdapter(Explorer.this,getChild(selectPath)));
			   				else{
			   					actionOpen(selectPath);

			   				}
							break;
						}
						
						case (MENU_ITEM_RENAME):
						{
							actionRename();
							break;
						}
						
						case (MENU_ITEM_COPY):
						{
							actionCopy();
							break;
						}
						
						case (MENU_ITEM_CUT):
						{
							actionCut();
							break;
						}
						
						case (MENU_ITEM_PASTE):
						{
							actionPaste();
							break;
						}
						
						case (MENU_ITEM_DELETE):
						{
							actionDelete();
							break;
						}
					
					}
					selectPath=null;
					select=-1;
				
					
				}
			});
	        // end context menu	********************************
	        
	        
	    }catch(Exception e){
        	Toast.makeText(this, "Error :  "+e.getMessage(), Toast.LENGTH_LONG).show();
        }
        }
    
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
	    if (keyCode == KeyEvent.KEYCODE_BACK)
	    {
	    	if( currentPath.equals("/") )
	    		System.exit( 0 );
	    	String parent=getParent( currentPath );
	    	if( parent == null )
	    		return true;
	    	list.setAdapter(new DirectoryAdapter(Explorer.this,getChild(parent)));
	        return true;
	    }
	    return super.onKeyDown(keyCode, event);
	}

    private String getParent( String path)
    {
    	return new File( path ).getParent();
    }
    private String getInfor(File file)
    {
    	try{
    		if(file.isFile())
    		{
    			return "File size : "+file.length()+" byte";
    		}
    		else
    		{
    			if(file.list()==null || file.list().length == 0)
    				return "Directory is empty";
    			return "Items count : "+file.list().length;
    		}
    	}catch(Exception e)
    	{
    		return e.toString();
    	}
    }
    public FileItem[] getChild(String parent)
    {
    	tv.setText("Current : "+parent);
		FileItem[] item=null;
		currentPath=parent;
		File file=new File(parent);
		String list[]=file.list();
		if(list==null || file.list().length == 0)
		{
			item=new FileItem[1];
			item[0]=new FileItem(false,false,"(Directory is empty)",null,"Nothing here","empty");
		}
		else
		{
			item=new FileItem[list.length];
			for(int i=0;i<list.length;i++)
			{
				File a=new File(currentPath+"/"+list[i]);
				item[i]=new FileItem(true,a.isFile(),a.getName(),currentPath+"/"+a.getName(),getInfor(a),null);//a.getPath());
			}
		}
		return item;
	}
 
    public boolean onCreateOptionsMenu(Menu menu)
    {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.mainmenu, menu);
        return true;
    }
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
    	super.onActivityResult(requestCode, resultCode, data);
    	actionRefresh();
    }
    public boolean onOptionsItemSelected(MenuItem item)
    {
    	switch(item.getItemId())
    	{
    		case R.id.copy:
    			if(select==-1)	break;
    			actionCopy();
    			break;
    		case R.id.exit:
    			System.exit(0);
    			break;
    		case R.id.rename:
    			actionRename();
    			break;
    		case R.id.refresh:
    			actionRefresh();
    			break;
    		case R.id.createfolder:
    			actionCreateFolder();
    			break;
    		case R.id.goup:
    			String parent=getParent(currentPath);
    			if(parent!=null)
    				list.setAdapter(new DirectoryAdapter(Explorer.this,getChild(parent)));
    			break;
    		case R.id.cut:
    			if(select==-1)break;
    			actionCut();
    			break;
    		case R.id.gotoDesktop:
    			list.setAdapter(new DirectoryAdapter(this,getChild("/")));
    			break;
    		case R.id.paste:
    			actionPaste();
    			break;
    		case R.id.delete:
    			actionDelete();
    			break;
    		case R.id.properties:
    			actionProperties();
    			break;
    		case R.id.about:
    			actionAbout();
    			break;
    		}
    		return true;
    }
    
    
    // action ************************************8888
    private void actionRefresh()
    {
    	list.setAdapter(new DirectoryAdapter(this,getChild(currentPath)));
    }
    private void actionAbout()
    {
    	Intent intent=new Intent(Explorer.this,android.explorer.activity.FormAbout.class);
		startActivityForResult(intent,delete);	
    }
    private void actionOpen(String path)
    {
    	MimeTypeMap tMimeType = MimeTypeMap.getSingleton();
    	String tMimeStr = tMimeType.getMimeTypeFromExtension(path.substring(path.length()-3).toLowerCase());
    	Intent intent=new Intent();
		Uri data = Uri.parse("file://"+path);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(android.content.Intent.ACTION_VIEW);
		intent.setDataAndType(data,tMimeStr);
		try 
		{
			startActivity(intent);
		} catch (Exception e)
		{
			Toast.makeText(this, "Can not find any program associate with this file.",Toast.LENGTH_LONG).show();
		}
    }
    private void actionDelete()
    {
    	final String selectPath = this.selectPath;
    	if(selectPath==null){
    		new ShowOkDialog(this,"You must select a item before continue.","Information",null);
    		return;
    	}
    	Log.v("debug", "selectPath "+ selectPath);
    	final File file=new File(selectPath);
    	if(file.isFile()){
    		Log.v("debug", "is file: "+ selectPath);
			
	    	new ShowYesNoDialog(this,"Are you sure want to delete the file "+selectPath+" ?","Confirm delete",new OnClickListener(){
				public void onClick(DialogInterface arg0, int arg1) {
					Log.v("debug", "begin delete file");
					if(file.delete()){
						Log.v("debug", "deleted file");
						Toast.makeText(Explorer.this, "Delete this file has finished successfully !", Toast.LENGTH_LONG).show();
					}else{
						Log.v("debug", "can't delete file");
						Toast.makeText(Explorer.this, "Delete this file has finished failed !", Toast.LENGTH_LONG).show();
					}
					list.setAdapter(new DirectoryAdapter(Explorer.this,getChild(currentPath)));
					
				}
	    	});
    	}else if (file.isDirectory()){
    		Log.v("debug", "is folder: "+ selectPath);
			
    		new ShowYesNoDialog(this,"Are you sure want to delete the file "+selectPath+" ?","Confirm delete",new OnClickListener(){
				public void onClick(DialogInterface arg0, int arg1) {
					Log.v("debug", "delete: new intent");
					Intent intent=new Intent(Explorer.this,android.explorer.activity.FolderDelete.class);
					Log.v("debug", "delete: putExtra: "+ selectPath);
					intent.putExtra("foldername", selectPath);
					Log.v("debug", "delete: startActivity");
					startActivityForResult(intent,delete);
					Log.v("debug", "delete: startactivity 1");
				}
	    	});
    	}
    	else
    	{
			Toast.makeText(Explorer.this, "Access failed", Toast.LENGTH_LONG).show();    		
    	}
    }
    private void actionRename(){
    	final File file=new File(selectPath);
    	new InputBox(this,"Enter new name !",file.getName(),new CallBack(){
			public void onOKClick() {}
			public void onOkClick(String value) {
				if(value!=null){
					try{
						File fileto=new File(file.getParent()+"/"+value);
						
						if(fileto.exists()){
							Toast.makeText(getApplicationContext(), "This name has been used by another file.", Toast.LENGTH_LONG).show();
						}else if(file.renameTo(fileto)){
							Toast.makeText(getApplicationContext(), "Renaming is successly.", Toast.LENGTH_LONG).show();
						}else{
							Toast.makeText(getApplicationContext(), "Renaming is failed.", Toast.LENGTH_LONG).show();
						}
					}catch(Exception e){
						Toast.makeText(getApplicationContext(), "Error "+e.getMessage(), Toast.LENGTH_LONG).show();
					}
				}
				list.setAdapter(new DirectoryAdapter(Explorer.this,getChild(currentPath)));
			}
    	}).show();
    }
    private void actionProperties(){
    	String selectPath=this.selectPath;
    	if(selectPath==null)selectPath=this.currentPath;
    	File file=new File(selectPath);
    	if(file.isFile()){
	    	Intent intent=new Intent(this,android.explorer.activity.FileProperties.class);
			intent.putExtra("filename",selectPath);
			startActivityForResult(intent,properpties);
    	}else{
    		Intent intent=new Intent(this,android.explorer.activity.FolderProperties.class);
    		intent.putExtra("foldername",selectPath);
			startActivityForResult(intent,properpties);
    	}
    }
    private void actionCreateFolder(){
    	new InputBox(this,"Enter the folder's name","",new CallBack(){
			public void onOKClick() {}
			public void onOkClick(String value) {
				if(value!=null){
					try{
						File file=new File(currentPath+"/"+value);
						if(file.exists()){
							Toast.makeText(getApplicationContext(), "This folder already exit.", Toast.LENGTH_LONG).show();
						}else if(file.mkdir()){
							Toast.makeText(getApplicationContext(), "Creating folder is successly.", Toast.LENGTH_LONG).show();
						}else{
							Toast.makeText(getApplicationContext(), "Creating folder is failed.", Toast.LENGTH_LONG).show();
						}
					}catch(Exception e){
						Toast.makeText(getApplicationContext(), "Error "+e.getMessage(), Toast.LENGTH_LONG).show();
					}
				}
				list.setAdapter(new DirectoryAdapter(Explorer.this,getChild(currentPath)));
			}
    	}).show();
    }
    private void actionCopy(){
    	if(selectPath==null)return;
		if(new File(selectPath).isFile())
			Toast.makeText(this, "The file "+selectPath +" will copy when you select command paste.", Toast.LENGTH_SHORT).show();
		else Toast.makeText(this, "The folder "+selectPath +" will copy when you select command paste.", Toast.LENGTH_SHORT).show();
		lastPath=selectPath;
		isCopy=true;
    }
    private void actionCut(){
		if(selectPath==null)return;
		if(new File(selectPath).isFile())
			Toast.makeText(this, "The file "+selectPath +" will move when you select command paste.", Toast.LENGTH_SHORT).show();
		else Toast.makeText(this, "The folder "+selectPath +" will move when you select command paste.", Toast.LENGTH_SHORT).show();
		lastPath=selectPath;
		isCopy=false;
    }
    private void actionPaste(){
    	if(lastPath==""){
    		Toast.makeText(this, "You must select a file or a folder and call command copy or cut before.", Toast.LENGTH_LONG).show();
    		return;
    	}
    	File src=new File(lastPath);
    	if(src.getParent()==currentPath){
    		Toast.makeText(this, "The dest folder is'n vaild.\nPlease select another folder.",Toast.LENGTH_LONG ).show();
    		return;
    	}
    	if(currentPath.indexOf(lastPath)>=0){
    		Toast.makeText(this, "The dest folder is'n vaild.\nPlease select another folder.",Toast.LENGTH_LONG ).show();
    		return;
    	}
    	if(isCopy){
    		Intent intent=new Intent(this,FileCopy.class);
    		intent.putExtra("filesource", lastPath);
    		intent.putExtra("folderdes", currentPath+"/"+src.getName());
    		startActivityForResult(intent, 0x000111);
    	}else{
    		File f1=new File(lastPath);
    		File f2=new File(currentPath+"/"+f1.getName());
    		try {
				if(f1.renameTo(f2)){
					Toast.makeText(this, "Operation has finished successfuly", Toast.LENGTH_LONG).show();
				}else{
					Toast.makeText(this, "Operation has finished failed", Toast.LENGTH_LONG).show();
				}
			} catch (Exception e) {
				Toast.makeText(this, "Error when execute the  command "+e.toString()+".", Toast.LENGTH_LONG).show();
				e.printStackTrace();
			}
    	}
    	actionRefresh();
    }
    // end action ***************************************
    
    
    // button on top **********************************
    public void onSdcardButtonClick(View target){
    	list.setAdapter(new DirectoryAdapter(Explorer.this,getChild("/mnt/sdcard")));
	}
    public void onBackFolderButtonClick(View target)
    {
       	String parent=getParent(currentPath);
	    if(parent!=null)
	    	list.setAdapter(new DirectoryAdapter(Explorer.this,getChild(parent)));
    }
    public void onRefreshButtonClick( View target)
    {
    	actionRefresh();    	
    }
    public void onSortButtonClick( View target)
    {
    	actionRefresh();    	
    }public void onSettingButtonClick( View target)
    {
    	actionRefresh();    	
    }
    // end button on top *******************************

	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		if (id == CONTEXT_MENU_ID) {
			return iconContextMenu.createMenu("File Options");
		}
		return super.onCreateDialog(id);}
	
}
